import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart';
import 'package:dio/dio.dart';
import 'package:projectone/link_url.dart';
import 'dart:convert';
import './bean/books_bean.dart';

class NetworkData {
  Dio dio = new Dio();

  getData(String url) async {
    var response = await dio.get('http://www.xbiqige.com/sort/dushi.html');
    //print(response.data);
    dom.Document document = parse(response.data);
    //var el=document.getElementsByTagName('a')[1];
    //print(el.text);
//    List name=document.querySelectorAll('a.novelname');
//    print(name);
    var lefts = document.querySelectorAll(".pt-ll-l"); //找到所有pt-ll-l节点
    for (int i = 0; i < lefts.length; i++) {
      String out = lefts[i]
          .querySelector("div>a")
          .attributes['title'].trim(); //获取书名
      print(out);
    }
  }

  Future<BookDetailBean> getBookDetail(String url) async {
    //print(url);
    //BookDetailBean bookDetailBean=new BookDetailBean(bookName, bookId, lastName, lastLink, author, type, bookCover, bookIntro, bookChapter)
    List<BookChapter> chapterList=new List();
    var response = await dio.get(url);
    dom.Document bookDoc = parse(response.data);
    var bookName=bookDoc.getElementsByClassName('header line')[0].querySelector('h1').text;
    //print(bookName);
    var leftInfo=bookDoc.getElementsByClassName('novelinfo-l');
    String lastName=leftInfo[0].querySelectorAll('ul > li')[5].text;
    String lastLink=urlApi.contentBaseUrl+
        leftInfo[0].querySelectorAll('ul > li')[5].querySelector('a')
            .attributes['href'].trim().replaceAll('/shu_', '').replaceAll('.html', '/');
    String author=leftInfo[0].querySelectorAll('ul > li')[0].text;
    //print(lastName+'&'+lastLink+'&'+author);
    String bookCover=urlApi.baseImgUrl+bookDoc.getElementsByClassName('novelinfo-r')[0].querySelector('a > img').attributes['src'];
    String bookId=bookDoc.getElementsByClassName('novelinfo-r')[0].querySelector('a').attributes['href'].trim()
    .replaceAll('/shu_', '').replaceAll('/', '');
    String intro=bookDoc.getElementsByClassName('body novelintro')[0].text;
    var chapter = bookDoc.getElementsByClassName('dirlist three clearfix')[1].querySelectorAll('li > a');
    for (int i = 0; i < chapter.length; i++) {
      String chapterLink=urlApi.contentBaseUrl+chapter[i].attributes['href'].trim().replaceAll('/shu_', '').replaceAll('.html', '/');
      //if(i<20)print(chapterLink);
      chapterList.add(new BookChapter(chapter[i].text, chapterLink));
    }
    return new BookDetailBean(bookName:bookName,bookId: bookId,lastName: lastName,lastLink: lastLink,author: author,bookCover: bookCover,bookIntro: intro, bookChapter: chapterList);
  }
  //获取章节内容
  Future<String> getBookContent(String url) async {
    var response = await dio.get(url);
    //print(response.data);
    Map<String, dynamic> aa = json.decode(response.data);
    //print(aa['info']);
//    dom.Document bookContent=parse(response.data);
//    var mumu=bookContent.querySelectorAll('.content');
//    for(int i=0;i< mumu.length;i++){
//      print(mumu[i].text);
//    }
    String ret = aa['info'].toString();

    //print(ret.replaceAll('<br>', '').replaceAll('\n', ''));
    return ret.replaceAll('<br>', '');
  }

  Future<List<BooksBean>> getBookList(String url,[String bookName]) async{
    //print(url+bookName);
    List<BooksBean> bookList=new List();
    var response;
    if(bookName!=null) response = await dio.get(url+bookName);
    else response=await dio.get(url);
    dom.Document document = parse(response.data);//将String 转换为document对象
    var content = document.querySelector(".librarylist");//找到标签中librarylist的节点，类选择器节点的查找前面要加个.
    var lefts = content.querySelectorAll(".pt-ll-l");//找到所有pt-ll-l节点
    var rights = content.querySelectorAll(".pt-ll-r");//找到所有pt-ll-r 节点
    int count = lefts.length > rights.length ? rights.length : lefts.length;//取最短数据，这里是为了保险，防止数组越界
    for (int i = 0; i < count; i++) {
      //在pt-ll-l，pt-ll-r 节点下找到目标数据
      BooksBean item = new BooksBean(
          lefts[i].querySelector("div>a>img").attributes['alt'].trim(),//获取书名
          urlApi.baseImgUrl+lefts[i].querySelector("div>a").attributes['href'].trim(),
          rights[i].querySelectorAll(".info>span")[1].text.trim(),//第二个span元素值,获取作者
          rights[i].querySelector(".last>a").attributes["href"].trim(),//href 属性值，最后一章的Url
          rights[i].querySelector(".last>a").text.trim(),//元素值，获取标题
          //rights[i].querySelectorAll(".info>span")[2].text.trim(),//第三个span元素值,获取小说分类
          rights[i].querySelectorAll(".info>span")[2].text.trim(),//第三个span元素值,获取小说分类
          urlApi.baseImgUrl+lefts[i].querySelector("div>a>img").attributes['src'].trim()//获取小说图片
           );//获取书URL
      bookList.add(item);
      //print(item.toString());
    }

    return bookList;
  }
  Future<List<BooksBean>> getBookCommend(String url) async{
    List<BooksBean> bookList=new List();
    var response=await dio.get(urlApi.baseImgUrl);
    dom.Document document = parse(response.data);//将String 转换为document对象
    var names=document.querySelectorAll('.n');
    var athor=document.querySelectorAll('.a');
    var last=document.querySelectorAll('.c');
    //int count = lefts.length > rights.length ? rights.length : lefts.length;//取最短数据，这里是为了保险，防止数组越界
    for (int i = 0; i < names.length; i++) {
      //在pt-ll-l，pt-ll-r 节点下找到目标数据
      BooksBean item = new BooksBean(
          names[i].querySelector("a").attributes['title'].trim(),//获取书名
          urlApi.baseImgUrl+names[i].querySelector("a").attributes['href'].trim(),
          athor[i].querySelector("a").text.trim(),//第二个span元素值,获取作者
          urlApi.baseImgUrl+last[i].querySelector("a").attributes["href"].trim(),//href 属性值，最后一章的Url
          '',//元素值，获取标题
          last[i].querySelector("a").attributes['title'].trim(),//没有分类
          ''//获取小说图片（没有图片）
      );
      bookList.add(item);
      //print(item.toString());
    }

    return bookList;
  }

  Future<List<BooksTypeListBean>>getBookListByType(String typeUrl) async{
    List<BooksTypeListBean> bookList=new List();
    var response=await dio.get(typeUrl);
    dom.Document document= parse(response.data);
    var info=document.querySelectorAll('p.info');
    var intro=document.querySelectorAll('p.intro');
    var last=document.querySelectorAll('p.last');
    var img=document.querySelectorAll('div.pt-ll-l');
    for(int i=0;i<info.length;i++){
      BooksTypeListBean item=new BooksTypeListBean(
      info[i].querySelector('a.novelname').text,
          urlApi.baseImgUrl+info[i].querySelector('a.novelname').attributes['href'].trim(),
          info[i].querySelectorAll('span')[1].querySelector('a').text.trim(),
          urlApi.baseImgUrl+last[i].querySelector('a').attributes['href'].trim(),
          last[i].querySelector('a').text,
          '',
          urlApi.baseImgUrl+img[i].querySelector('a > img').attributes['src'].trim(),
          intro[i].text.trim().replaceAll('<br>', ''));
      bookList.add(item);
      //print(item.toString());
    }
    return bookList;
  }
}
